package com.briup.estore.web.servlet;

import com.briup.estore.bean.Book;
import com.briup.estore.service.BookService;
import com.briup.estore.service.Impl.BookServiceImpl;
import com.briup.estore.vm.BookVM1;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/confirmOrder")
public class ConfirmOrderServlet extends HttpServlet {
    private BookService bookService;
    {
        bookService = new BookServiceImpl();
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取书籍id和num之间的关系
        String str = req.getParameter("bookIdAndNum");
        // 处理数据
        String[] bookIdAndNum = {};
        if (str!=null && !"".equals(str)){
            bookIdAndNum = str.split(",");
        }
        // 根据书籍id查询书籍信息
        // 准备一个纯书籍的列表
        List<BookVM1> bookList = new ArrayList<>();
        for (String s : bookIdAndNum) {
            String s1 = s.split("-")[0];
            int i = Integer.parseInt(s1);
            Book book = bookService.findBookById(i);
            // 放入对象
            BookVM1 bookVM1 = new BookVM1();
            bookVM1.setId(book.getId());
            bookVM1.setName(book.getName());
            bookVM1.setAuthor(book.getAuthor());
            bookVM1.setPrice(book.getPrice());
            bookVM1.setCategoryId(book.getCategoryId());
            bookVM1.setImage(book.getImage());
            bookVM1.setPublisher(book.getPublisher());
            bookVM1.setPubdate(book.getPubdate());
            bookVM1.setDescription(book.getDescription());
            String s2 = s.split("-")[1];
            int i1 = Integer.parseInt(s2);
            bookVM1.setNum(i1);
            bookVM1.setTotal(new BigDecimal(i1).multiply(new BigDecimal(bookVM1.getPrice())).setScale(2).doubleValue());

            bookList.add(bookVM1);
        }
        // 存入到session中并做跳转
        HttpSession session = req.getSession();
        session.setAttribute("bookVmList",bookList);
        //
        resp.sendRedirect("confirm");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
